

package zmee.pur.src.formplugin;

import java.math.BigDecimal;
import java.util.EventObject;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import kd.bos.bill.BillOperationStatus;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.resource.ResManager;
import kd.bos.entity.datamodel.AbstractFormDataModel;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.form.CloseCallBack;
import kd.bos.form.ConfirmCallBackListener;
import kd.bos.form.FormShowParameter;
import kd.bos.form.MessageBoxOptions;
import kd.bos.form.MessageBoxResult;
import kd.bos.form.MessageTypes;
import kd.bos.form.ShowType;
import kd.bos.form.events.BeforeDoOperationEventArgs;
import kd.bos.form.events.ClosedCallBackEvent;
import kd.bos.form.events.MessageBoxClosedEvent;
import kd.bos.form.events.PreOpenFormEventArgs;
import kd.bos.form.operate.AbstractOperate;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.scm.common.util.SrmCommonUtil;
import kd.scm.pds.common.extplugin.ExtPluginContext;
import kd.scm.pds.common.extplugin.ExtPluginFactory;
import kd.scm.pds.common.extplugin.IExtPluginHandler;
import kd.scm.pds.common.util.ExtParameterUtils;
import kd.scm.pds.common.util.OpenFormUtils;
import kd.scm.pds.common.util.PdsCommonUtils;
import kd.scm.src.common.score.SrcScoreContext;
import kd.scm.src.common.score.SrcScoreFacade;
import kd.scm.src.common.score.SrcScoreHelper;
import org.apache.commons.lang.StringUtils;
/**
* @author lijiawang
* @Date 2022/12/5 16:44
* @Description:评标助手
*/
public class SrcScoreassistBillPlugin extends AbstractFormPlugin {
    private boolean isChanging = false;


    public void preOpenForm(PreOpenFormEventArgs e) {
        FormShowParameter showParameter = (FormShowParameter)e.getSource();
        String baseType = PdsCommonUtils.object2String(showParameter.getCustomParams().get("basetype"), "");
        if ("4".equals(baseType)) {
            showParameter.setCaption(ResManager.loadKDString("资质预审助手", "SrcScoreAssist_8", "scm-src-formplugin", new Object[0]));
        } else if ("7".equals(baseType)) {
            showParameter.setCaption(ResManager.loadKDString("资质后审助手", "SrcScoreAssist_9", "scm-src-formplugin", new Object[0]));
        }

    }

    public void afterCreateNewData(EventObject e) {
        super.afterCreateNewData(e);
        Map<String, Object> paramMap = this.getView().getFormShowParameter().getCustomParams();
        String baseType = PdsCommonUtils.object2String(paramMap.get("basetype"), "");
        if ("4".equals(baseType)) {
            this.getView().setVisible(false, new String[]{"quoteanalyse"});
        } else if ("7".equals(baseType)) {
            this.getView().setVisible(false, new String[]{"quoteanalyse"});
        }

        long projectId = this.getProjectId();
        if (projectId > 0L) {
            SrcScoreContext context = SrcScoreFacade.createScoreContext(this.getView());
            context.setProjectId(projectId);
            paramMap.put("project", projectId);
            context.setParamMap(paramMap);
            this.getModel().setValue("projectid", projectId);
            this.refreshData(context);
        } else {
            OpenFormUtils.openDynamicPage(this.getView(), "src_scorequery", ShowType.NonModal, paramMap, new CloseCallBack(this, "query"));
        }

    }

    protected void refreshData(SrcScoreContext context) {
        if (context.getParamMap() == null || context.getParamMap().size() == 0) {
            context.setParamMap(this.getView().getFormShowParameter().getCustomParams());
        }

        SrcScoreFacade.getSelectFields(context);
        SrcScoreFacade.getQFilter(context);
        SrcScoreFacade.queryScoreData(context);
        SrcScoreFacade.loadScoreData(context);
    }

    public void propertyChanged(PropertyChangedArgs evt) {
        super.propertyChanged(evt);
        String propertyName = evt.getProperty().getName();
        Object newValue = evt.getChangeSet()[0].getNewValue();
        int rowIndex = evt.getChangeSet()[0].getRowIndex();
        byte var6 = -1;
        switch(propertyName.hashCode()) {
            case 3387378:
                if (propertyName.equals("note")) {
                    var6 = 2;
                }
                break;
            case 111972721:
                if (propertyName.equals("value")) {
                    var6 = 1;
                }
                break;
            case 315913228:
                if (propertyName.equals("isfitted")) {
                    var6 = 0;
                }
        }

        switch(var6) {
            case 0:
                this.setVualeByIsFitted(newValue, rowIndex);
                this.inputControl(rowIndex);
                break;
            case 1:
                if (StringUtils.isEmpty(String.valueOf(newValue))) {
                    break;
                }

                if (!SrcScoreHelper.isNumberValue(String.valueOf(newValue))) {
                    this.getModel().setValue("value", (Object)null, rowIndex);
                    break;
                }
            case 2:
                if (this.isChanging) {
                    return;
                }

                this.inputControl(rowIndex);
        }

    }

    private void setVualeByIsFitted(Object newValue, int rowIndex) {
        this.isChanging = true;
        if (newValue == null) {
            this.getModel().setValue("note", (Object)null, rowIndex);
            this.getModel().setValue("value", (Object)null, rowIndex);
            this.getModel().setValue("scorerscored", "0", rowIndex);
        } else {
            DynamicObjectCollection cols = this.getModel().getEntryEntity("score_entry");
            this.setIsFittedValue(cols);
            DynamicObject index = ((DynamicObject)cols.get(rowIndex)).getDynamicObject("index");
            if (!Objects.isNull(index)) {
                if (index.getBoolean("isfitted")) {
                    if ((Boolean)newValue) {
                        this.getModel().setValue("note", ResManager.loadKDString("合格", "SrcScoreAssist_5", "scm-src-formplugin", new Object[0]), rowIndex);
                        if ("1".equals(index.getString("scoremethod"))) {
                            this.getModel().setValue("value", "100", rowIndex);
                        } else {
                            Object value = index.getBigDecimal("score").setScale(2, 5);
                            this.getModel().setValue("value", value, rowIndex);
                        }
                    } else {
                        this.getModel().setValue("note", ResManager.loadKDString("不合格", "SrcScoreAssist_6", "scm-src-formplugin", new Object[0]), rowIndex);
                        this.getModel().setValue("value", "0", rowIndex);
                    }

                    this.getModel().setValue("scorerscored", "1", rowIndex);
                    this.isChanging = false;
                }
            }
        }
    }

    private void setIsFittedValue(DynamicObjectCollection cols) {
        int i = 0;

        for(Iterator var3 = cols.iterator(); var3.hasNext(); ++i) {
            DynamicObject col = (DynamicObject)var3.next();
            DynamicObject index = col.getDynamicObject("index");
            if (Objects.isNull(index)) {
                return;
            }

            if (!index.getBoolean("isfitted")) {
                this.getModel().beginInit();
                this.getModel().setValue("isfitted", false, i);
                this.getModel().endInit();
            }
        }

    }

    protected void inputControl(int rowIndex) {
        if (!this.isChanging) {
            this.isChanging = true;
            SrcScoreFacade.inputControl(this.getView(), rowIndex);
            this.isChanging = false;
        }
    }

    public void beforeDoOperation(BeforeDoOperationEventArgs args) {
        super.beforeDoOperation(args);
        String opKey = ((AbstractOperate)args.getSource()).getOperateKey();
        args.setCancel(true);
        byte var4 = -1;
        switch(opKey.hashCode()) {
            case -1412808770:
                if (opKey.equals("answer")) {
                    var4 = 8;
                }
                break;
            case -1389262053:
                if (opKey.equals("biddoc")) {
                    var4 = 9;
                }
                break;
            case -891535336:
                if (opKey.equals("submit")) {
                    var4 = 4;
                }
                break;
            case -864330637:
                if (opKey.equals("analyse")) {
                    var4 = 6;
                }
                break;
            case 3059573:
                if (opKey.equals("copy")) {
                    var4 = 2;
                }
                break;
            case 3522941:
                if (opKey.equals("save")) {
                    var4 = 3;
                }
                break;
            case 94756344:
                if (opKey.equals("close")) {
                    var4 = 11;
                }
                break;
            case 107944136:
                if (opKey.equals("query")) {
                    var4 = 0;
                }
                break;
            case 1197722116:
                if (opKey.equals("suggestion")) {
                    var4 = 5;
                }
                break;
            case 1427905143:
                if (opKey.equals("quoteanalyse")) {
                    var4 = 7;
                }
                break;
            case 1586809669:
                if (opKey.equals("scorebysup")) {
                    var4 = 10;
                }
                break;
            case 1679267395:
                if (opKey.equals("autoscore")) {
                    var4 = 1;
                }
        }

        switch(var4) {
            case 0:
                this.scoreQuery();
                break;
            case 1:
                this.autoScore();
                break;
            case 2:
                this.scoreCopy();
                break;
            case 3:
                this.saveScoreData();
                break;
            case 4:
                this.submitScoreData();
                break;
            case 5:
                this.submitSuggestion();
                break;
            case 6:
                this.openAnalyse();
                break;
            case 7:
                this.openQuoteAnalyse();
                break;
            case 8:
                this.openAnswer();
                break;
            case 9:
                this.openBiddoc();
                break;
            case 10:
                this.scoreBySup();
                break;
            case 11:
                PdsCommonUtils.refreshParentView(this.getView());
                this.getView().close();
        }

    }

    private void scoreBySup() {
        IExtPluginHandler openScoreBySupHandle = (IExtPluginHandler)ExtPluginFactory.getInstance().getExtPluginInstance("ISrcScoreOpenBySup");
        if (null != openScoreBySupHandle) {
            ExtPluginContext context = new ExtPluginContext();
            context.setView(this.getView());
            openScoreBySupHandle.process(context);
        }

    }

    private void scoreQuery() {
        OpenFormUtils.openDynamicPage(this.getView(), "src_scorequery", ShowType.NonModal, (Map)null, new CloseCallBack(this, "query"));
    }

    private void autoScore() {
        DynamicObjectCollection rows = ((AbstractFormDataModel)this.getModel()).getEntryEntity("score_entry");
        if (rows != null && rows.size() != 0) {
            String bidName = ((DynamicObject)this.getModel().getValue("project")).getString("bidname");
            this.getView().showConfirm(String.format(ResManager.loadKDString("%1$s 将自动评分，请先保存当前评分结果，是否继续？", "SrcScoreAssist_1", "scm-src-formplugin", new Object[0]), bidName), MessageBoxOptions.OKCancel, new ConfirmCallBackListener("autoscore"));
        } else {
            this.getView().showTipNotification(ResManager.loadKDString("您没有待评标的项目！", "SrcScoreAssist_0", "scm-src-formplugin", new Object[0]));
        }

    }

    private void openAnalyse() {
        Map<String, Object> paramMap = this.getView().getFormShowParameter().getCustomParams();
        DynamicObjectCollection rows = ((AbstractFormDataModel)this.getModel()).getEntryEntity("score_entry");
        Set<Long> projectSet = (Set)rows.stream().map((e) -> {
            return e.getLong("project.id");
        }).collect(Collectors.toSet());
        if (projectSet != null && projectSet.size() > 0) {
            QFilter qFilter = new QFilter("project", "in", projectSet);
            OpenFormUtils.openListPage(this.getView(), "src_scoreanalyse", ShowType.MainNewTabPage, paramMap, qFilter, (CloseCallBack)null);
        } else {
            this.getView().showTipNotification(ResManager.loadKDString("请选择寻源项目！", "SrcScoreAssist_7", "scm-src-formplugin", new Object[0]));
        }

    }

    private void openQuoteAnalyse() {
        Map<String, Object> paramMap = this.getView().getFormShowParameter().getCustomParams();
        DynamicObjectCollection rows = ((AbstractFormDataModel)this.getModel()).getEntryEntity("score_entry");
        Set<Long> projectSet = (Set)rows.stream().map((e) -> {
            return e.getLong("project.id");
        }).collect(Collectors.toSet());
        if (projectSet != null && projectSet.size() > 0) {
            QFilter qFilter = new QFilter("project", "in", projectSet);
            OpenFormUtils.openListPage(this.getView(), "src_analysetool", ShowType.MainNewTabPage, paramMap, qFilter, (CloseCallBack)null);
        } else {
            this.getView().showTipNotification(ResManager.loadKDString("请选择寻源项目！", "SrcScoreAssist_7", "scm-src-formplugin", new Object[0]));
        }

    }

    private void openAnswer() {
        int entryIndex = this.getModel().getEntryCurrentRowIndex("score_entry");
        DynamicObject row = this.getModel().getEntryRowEntity("score_entry", entryIndex);
        long projectId = 0L;
        if (row != null) {
            projectId = row.getLong("project.id");
        }

        if (projectId != 0L) {
            Map<String, Object> customParams = new HashMap(1);
            customParams.put("project", projectId);
            QFilter qFilter = new QFilter("project", "=", projectId);
            OpenFormUtils.openListPage(this.getView(), "src_question", ShowType.MainNewTabPage, customParams, qFilter, (CloseCallBack)null);
        } else {
            OpenFormUtils.openListPage(this.getView(), "src_question", ShowType.MainNewTabPage, (Map)null, (QFilter)null, (CloseCallBack)null);
        }

    }

    private void saveScoreData() {
        SrcScoreContext context = SrcScoreFacade.createScoreContext(this.getView());
        context.setShowMessage(true);
        SrcScoreFacade.saveScoreData(context);
    }

    private void submitScoreData() {
        if (this.isValidate()) {
            SrcScoreContext context = SrcScoreFacade.createScoreContext(this.getView());
            Map<String, Object> paramMap = this.getView().getFormShowParameter().getCustomParams();
            context.setParamMap(paramMap);
            context.setProjectId(this.getProjectId());
            boolean isNeedSuggestion = this.isNeedSuggestion();
            if (isNeedSuggestion) {
                context.setShowMessage(false);
            } else {
                context.setShowMessage(true);
            }

            SrcScoreFacade.submitScoreData(context);
            if (!context.isCommitSucced()) {
                this.getView().showMessage(context.getCommitMessage());
            } else {
                if (isNeedSuggestion) {
                    OpenFormUtils.openDynamicPage(this.getView(), "src_submitsuggestion", ShowType.Modal, this.getView().getFormShowParameter().getCustomParams(), (CloseCallBack)null);
                } else if (context.isCommitSucced()) {
                    PdsCommonUtils.refreshParentView(this.getView());
                    this.getView().close();
                }

            }
        }
    }

    private boolean isValidate() {
        int i = 1;
        boolean isValidate = true;
        StringBuilder msgBuilder = new StringBuilder();

        DynamicObjectCollection cols = this.getModel().getEntryEntity("score_entry");
        StringBuilder scoreBuilder = new StringBuilder();
        for(Iterator var5 = cols.iterator(); var5.hasNext(); ++i) {
            DynamicObject col = (DynamicObject)var5.next();
            boolean scoreed = col.getBoolean("scorerscored");
            if (scoreed) {
                String value = col.getString("value");//评估值

                if (!SrcScoreHelper.isNumberValue(String.valueOf(value))) {
                    msgBuilder.append(ResManager.loadKDString(String.format("第%1$s行输入的值不合法", i), "SrcScoreAssist_10", "scm-src-formplugin", new Object[0]));
                    msgBuilder.append("\r\n");
                }else if(!isNeeScoorerscore(col,scoreBuilder,i)){
                }
            }
        }

        if (msgBuilder.length() > 0) {
            this.getView().showMessage(ResManager.loadKDString("提交失败", "SrcScoreAssist_11", "scm-src-formplugin", new Object[0]), msgBuilder.toString(), MessageTypes.Commit);
            isValidate = false;
        }else  if (scoreBuilder.length() > 0) {
            this.getView().showMessage(scoreBuilder.toString());
            isValidate = false;
        }

        return isValidate;
    }

    private boolean isNeeScoorerscore(DynamicObject col,StringBuilder scoreBuilder ,int index){
        //获取评分指标
        DynamicObject indexf = col.getDynamicObject("index");
        DynamicObject indexf7 = BusinessDataServiceHelper.loadSingle(indexf.getPkValue(), "src_indexf7");
        //获取指标类型
        DynamicObject indextype = indexf7.getDynamicObject("indextype");
        DynamicObject type = BusinessDataServiceHelper.loadSingle(indextype.getPkValue(), "src_indexclass");

        String number = type.getString("number");
        if (number.equals("SYS007") || number.equals("SYS003")) {
            //评分指标
            DynamicObject dex = col.getDynamicObject("index");
            BigDecimal scorerscore = col.getBigDecimal("scorerscore");//实际得分
            //评标任务(后台元数据)
            DynamicObject project = col.getDynamicObject("project");
            DynamicObject supplier = col.getDynamicObject("supplier");
            QFilter qFilter= new QFilter("project.id", QCP.equals, project.getPkValue());
            qFilter.and(new QFilter("supplier.id", QCP.equals,supplier.getPkValue()));
            qFilter.and(new QFilter("indextype.id",QCP.equals,type.getPkValue()));
            DynamicObject aptitude = BusinessDataServiceHelper.loadSingle("src_scoretask", "id",qFilter.toArray());
            DynamicObject scoretask = BusinessDataServiceHelper.loadSingle(aptitude.getPkValue(), "src_scoretask");
            //指标明细
            DynamicObjectCollection srcEntry = scoretask.getDynamicObjectCollection("entry");
            for (int i = 0; i < srcEntry.size(); i++) {
                DynamicObject ntry = srcEntry.get(i);
                //指标
                DynamicObject ndex = ntry.getDynamicObject("index");
                if (dex.getPkValue().toString().equals(ndex.getPkValue().toString())) {
                    //根据指标获取子单据体
                    DynamicObjectCollection subentry = ntry.getDynamicObjectCollection("subentry");
                    for (DynamicObject enty : subentry) {
                        //评委是否已评分
                        if (enty.getBoolean("scorerscored")) {
                            BigDecimal score = enty.getBigDecimal("scorerscore");
                            if(scorerscore.compareTo(score)==0){
                            }else{
                                DynamicObject scorer = enty.getDynamicObject("scorer");
                                if(number.equals("SYS007")) {
                                    scoreBuilder.append("您的第"+index+"行资质评分结果与" + scorer.getString("name") + "专家不一致，请协商后重新打分！");
                                    scoreBuilder.append("\r\n");
                                }else if(number.equals("SYS003")){
                                    scoreBuilder.append("您的第"+index+"行资信标评分结果与"+ scorer.getString("name") + "专家不一致，请协商后重新打分！");
                                    scoreBuilder.append("\r\n");
                                }
                            }
                        }

                    }
                }
            }
            if(scoreBuilder.length()>0){
                return false;
            }
        }
        return true;
    }

    private boolean isNeedSuggestion() {
        Map<String, Object> paramMap = this.getView().getFormShowParameter().getCustomParams();
        if (null != paramMap && paramMap.get("project") != null) {
            QFilter qfilters = new QFilter("id", "=", PdsCommonUtils.object2Long(paramMap.get("project")));
            DynamicObject projectObj = QueryServiceHelper.queryOne("src_project", "srctype.id,id", qfilters.toArray());
            if (null == projectObj) {
                return false;
            } else {
                String isneedsuggestion = null;
                String baseType = PdsCommonUtils.object2String(paramMap.get("basetype"), "");
                if (baseType.equals("4")) {
                    isneedsuggestion = "isneedsuggestion";
                } else if (baseType.equals("7")) {
                    isneedsuggestion = "isneedsuggestion2";
                } else {
                    isneedsuggestion = "isneedsuggestion3";
                }

                return ExtParameterUtils.convertToBoolen(ExtParameterUtils.getExtParameterValueById("pds_flowconfig", projectObj.getLong("srctype.id"), isneedsuggestion, false,projectObj.getLong("id")));
            }
        } else {
            return false;
        }
    }

    private void submitSuggestion() {
        SrcScoreContext context = SrcScoreFacade.createScoreContext(this.getView());
        context.setShowMessage(false);
        SrcScoreFacade.saveScoreData(context);
        OpenFormUtils.openDynamicPage(this.getView(), "src_submitsuggestion", ShowType.Modal, this.getView().getFormShowParameter().getCustomParams(), (CloseCallBack)null);
    }

    private void openBiddoc() {
        Map<String, Object> paramMap = this.getView().getFormShowParameter().getCustomParams();
        long projectId = PdsCommonUtils.object2Long(paramMap.get("project"));
        if (projectId == 0L) {
            int entryIndex = this.getModel().getEntryCurrentRowIndex("score_entry");
            DynamicObject row = this.getModel().getEntryRowEntity("score_entry", entryIndex);
            if (row != null) {
                projectId = row.getLong("project.id");
            }
        }

        if (projectId > 0L) {
            paramMap.put("project", projectId);
            OpenFormUtils.openBillPage(this.getView(), "src_bidassess_doc", projectId, BillOperationStatus.VIEW, ShowType.MainNewTabPage, paramMap, (CloseCallBack)null);
        } else {
            this.getView().showTipNotification(ResManager.loadKDString("请选择寻源项目！", "SrcScoreAssist_7", "scm-src-formplugin", new Object[0]));
        }

    }

    private void scoreCopy() {
        long projectId = SrmCommonUtil.getPkValue((DynamicObject)this.getModel().getValue("project"));
        Map<String, Object> paraMap = new HashMap();
        paraMap.put("project", projectId);
        CloseCallBack closeCallBack = new CloseCallBack(this, "copy");
        OpenFormUtils.openDynamicPage(this.getView(), "src_corecopy", ShowType.Modal, paraMap, closeCallBack);
    }

    public void closedCallBack(ClosedCallBackEvent evt) {
        super.closedCallBack(evt);
        String actionId = evt.getActionId();
        byte var4 = -1;
        switch(actionId.hashCode()) {
            case 3059573:
                if (actionId.equals("copy")) {
                    var4 = 1;
                }
                break;
            case 107944136:
                if (actionId.equals("query")) {
                    var4 = 0;
                }
        }

        switch(var4) {
            case 0:
                this.scoreQuery(evt);
                break;
            case 1:
                if (evt.getReturnData() != null) {
                    SrcScoreContext context = SrcScoreFacade.createScoreContext(this.getView());
                    SrcScoreFacade.afterCopyScore(context);
                    this.refreshData(context);
                }
        }

    }

    private void scoreQuery(ClosedCallBackEvent evt) {
        Object returnData = evt.getReturnData();
        if (returnData instanceof SrcScoreContext) {
            long projectId = ((SrcScoreContext)returnData).getProjectId();
            if (projectId == 0L) {
                this.getModel().setValue("projectid", (Object)null);
            } else {
                this.getModel().setValue("projectid", projectId);
            }

            this.refreshData((SrcScoreContext)returnData);
        } else {
            this.getModel().setValue("projectid", (Object)null);
        }
    }

    public void confirmCallBack(MessageBoxClosedEvent evt) {
        super.confirmCallBack(evt);
        if (evt.getResult() == MessageBoxResult.Yes) {
            if (evt.getCallBackId().equals("autoscore")) {
                this.autoScoreConfirm();
            }

        }
    }

    private void autoScoreConfirm() {
        long projectId = SrmCommonUtil.getPkValue((DynamicObject)this.getModel().getValue("project"));
        SrcScoreContext context = SrcScoreFacade.createScoreContext(this.getView());
        context.setShowMessage(true);
        context.setProjectId(projectId);
        SrcScoreFacade.autoScoreForProject(context);
        this.refreshData(context);
    }

    private long getProjectId() {
        Map<String, Object> paramMap = this.getView().getFormShowParameter().getCustomParams();
        if (null == paramMap) {
            return 0L;
        } else {
            long projectId = PdsCommonUtils.object2Long(paramMap.get("project"));
            if (projectId > 0L) {
                return projectId;
            } else {
                long pkId = PdsCommonUtils.object2Long(paramMap.get("pkId"));
                return pkId;
            }
        }
    }
}
